<?php
/**
 * Created by PhpStorm.
 * User: eugene
 * Date: 2018/5/22
 * Time: 13:49
 */

namespace App\Services;


use App\Repos\MemberRepo;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

class FriendService
{
    protected $user,$client,$token;
    private $apis=[
        'followUser'=>'api/community/watch/insertUserWatchInfo',
        'followers'=>'api/community/watch/findAllWantchingInfo',
    ];
    
    public function __construct($token)
    {
        $config = config('car.api_config');
        $host=$config['social_host'];
    
        $this->token=$token;
        $this->client = new Client(['base_uri'=>$host,'timeout'  => 3.0,'headers'=>[
            'token'=>$token,
            'x-client-id'=>'APP',
        ]]);
        
    }
    
    public function follow($who)
    {
        if(env('APP_ENV') == 'local'){
            return true;
        }
        $query = [
            'json'=>[
                'watchedUid'=>$who,
            ],
        ];
        
        $response = $this->client->post($this->apis['followUser'],$query);
        
        $body = json_decode((string)$response->getBody(),true);
    
        if(env('APP_DEBUG'))Log::info('friend-follow request:'.(string)$response->getBody().'who:'.$who);
        
        if(!\is_array($body) || $body['resultCode'] != 200 ){
            if(env('APP_DEBUG'))Log::error('friend-follow api request error:'.(string)$response->getBody());
            return false;
        }
        
        return $body['data'] > 0 ;
        
    }
    
    public function followers()
    {
        if(env('APP_ENV') == 'local'){
            return [];
        }
        $response = $this->client->get($this->apis['followers'],[
            'query'=>[
                'limit'=>100,
            ],
        ]);
        
        
        $body = json_decode((string)$response->getBody(),true);
    
        if(env('APP_DEBUG'))Log::info('friend-followers request:'.(string)$response->getBody());
        
        if(!\is_array($body) || $body['resultCode'] != 200){
            if(env('APP_DEBUG'))Log::error('friend-followers api request error'.(string)$response->getBody());
            return [];
        }
        
        $list = $body['data']['rows'];
        
        //将外部关系同步到应用内
        $follower_ids = [];
        foreach ($list as $rel) {
            $follower_ids[]=$rel['watchedUid'];
        }
        return $follower_ids;
    }
    

}